﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using DevExpress.Xpo;
using System.ComponentModel;

namespace EasyXaf.Sample.Module.BusinessObjects;

[MapInheritance(MapInheritanceType.ParentTable)]
[DefaultProperty(nameof(UserName))]
public class ApplicationUser : PermissionPolicyUser, ISecurityUserWithLoginInfo, IObjectSpaceLink
{
    private Company _company;
    private IList<Tianqi> tianqiList;

    [DataSourceProperty(nameof(CompanyDataSource))]
    public Company Company
    {
        get => _company;
        set => _company = value;
    }

    [Browsable(false)]
    public IList<Company> CompanyDataSource
    {
        get => ((IObjectSpaceLink)this).ObjectSpace.GetObjectsQuery<Company>().Take(20).ToList();
    }

    [System.ComponentModel.DisplayName("天气")]
    public IList<Tianqi> TianqiList
    {
        get => tianqiList ??= ((IObjectSpaceLink)this).ObjectSpace.GetObjects<Tianqi>();
        set => tianqiList = value;
    }

    public ApplicationUser(Session session) : base(session) { }

    [Browsable(false)]
    [Aggregated, Association("User-LoginInfo")]
    public XPCollection<ApplicationUserLoginInfo> LoginInfo
    {
        get { return GetCollection<ApplicationUserLoginInfo>(nameof(LoginInfo)); }
    }

    IEnumerable<ISecurityUserLoginInfo> IOAuthSecurityUser.UserLogins => LoginInfo.OfType<ISecurityUserLoginInfo>();

    IObjectSpace IObjectSpaceLink.ObjectSpace { get; set; }

    ISecurityUserLoginInfo ISecurityUserWithLoginInfo.CreateUserLoginInfo(string loginProviderName, string providerUserKey)
    {
        ApplicationUserLoginInfo result = new ApplicationUserLoginInfo(Session);
        result.LoginProviderName = loginProviderName;
        result.ProviderUserKey = providerUserKey;
        result.User = this;
        return result;
    }
}
